package com.ideafactory.client.utils.power;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.ideafactory.client.ybservice.APP;
import com.xboot.stdcall.posix;

import java.util.Calendar;

public class OnOffTool {
	
	public static final String PREFS_NAME = "SaveMyTime";
	
	public static boolean mbOpenOnOff = false;
	
	public static void setEnabled(byte on_h, byte on_m, byte off_h, byte off_m){
		try {
			SharedPreferences sp = APP.getAPP().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
			Editor editor = sp.edit();
			editor.putInt("onHour", on_h);
			editor.putInt("onMinute", on_m);
			editor.putInt("offHour", off_h);
			editor.putInt("offMinute", off_m);
			editor.putBoolean("countTime", true);
			mbOpenOnOff = true;
			editor.commit();
			
			setPowerOnOff(on_h, on_m, off_h, off_m, (byte)3);
		} catch (Exception e) {

		}
	}
	
	public static void setDisabled(){
		SharedPreferences sp = APP.getAPP().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
		mbOpenOnOff = sp.getBoolean("countTime", false);

		byte on_h = (byte) sp.getInt("onHour", 0);
		byte on_m = (byte)  sp.getInt("onMinute", 3);
		byte off_h = (byte) sp.getInt("offHour", 0);
		byte off_m = (byte) sp.getInt("offMinute", 3);
		
		
		setPowerOnOff(off_h, off_m, on_h, on_m, (byte) 0);
		if (mbOpenOnOff) {
			Editor editor = sp.edit();
			editor.putBoolean("countTime", false);
			mbOpenOnOff = false;
			editor.commit();
		}
	}
	
	 /**
   	 * 所有时间都是相对时间，（关机时间=实际关机时间-当前时间）
   	 * （开机时间=实际开机时间-当前时间-关机时间）
   	 * @param off_h 关机小时
   	 * @param off_m 关机分钟
   	 * @param on_h 开机小时
   	 * @param on_m 开机分钟
   	 * @param enable 自动开关机状态  0：关     3：开
   	 * @return
   	 */
   	public static int setPowerOnOff(byte off_h, byte off_m, byte on_h, byte on_m, byte enable) {
   		int fd, ret;
   		//  byte buf[] = { 0, 3, 0, 3 };
   		fd = posix.open("/dev/McuCom", posix.O_RDWR, 0666);
   		ret = posix.poweronoff(off_h, off_m, on_h, on_m, enable, fd);
		posix.close(fd);
		return 0;
   	}
   	
   	private static String getCurTime() {
		String time = "";
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int day = c.get(Calendar.DAY_OF_MONTH);
		int hour = c.get(Calendar.HOUR_OF_DAY);
		int minute = c.get(Calendar.MINUTE);
		int second = c.get(Calendar.SECOND);
		time = String.valueOf(year) + "-" + String.valueOf(month) + "-" + String.valueOf(day) + " " + String.valueOf(hour) + ":" + String.valueOf(minute) + ":" + String.valueOf(second);
		return time;
	}
}
